#!/usr/bin python
# -*- coding: utf-8 -*-
# @Time    : 2024/5/10 15:36
# @Author  : hhr
import os
import uuid
from datetime import timedelta
import pymysql, datetime, subprocess, calendar, xlrd
from chinese_calendar import is_workday
from openpyxl import Workbook
from openpyxl.styles import Alignment, Font
from openpyxl.styles.borders import Border, Side
from administrative.public_file import PDFConverter
from administrative.models import Topicsattachments
from administrative.utils import send_mssage
from correspondence.models import InboxInfo, InboxInfoPeople
from finance.models import TravelApply
from personal_center.models import User


class AutomaticScheduling():
    def __init__(self, development, types):
        self.conn = pymysql.connect(host="localhost", port=3306, user='root', password='123456' if development == 'test' else 'jsyy2021', db="administration", use_unicode=True, charset='utf8')
        self.cur = self.conn.cursor()
        self.duty_leader_list = []
        self.SchedulingList = []
        self.meseage_tel_li = []
        if types == "pre_scheduling":
            self.OperationTable = "personal_center_schedulingcopy"
        else:
            self.OperationTable = "personal_center_scheduling"
        print("self.OperationTable: ",self.OperationTable)

    def get_weekday(self, date_str):
        """根据日期判断是周几"""
        date_obj = datetime.datetime.strptime(date_str, "%Y-%m-%d")
        weekday = date_obj.weekday()
        weekday_str = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"]
        return weekday_str[weekday]

    def DateJudgment(self, current_date):
        """判断所传日期是否是工作日"""
        if is_workday(current_date):
            return 1
        else:
            return 2

    def UpgradeInstallationPackage(self):
        """升级判断日期是否是工作日的库"""
        subprocess.call("pip3 uninstall chinesecalendar", shell=True)
        subprocess.call("pip3 install chinesecalendar -i https://pypi.tuna.tsinghua.edu.cn/simple", shell=True)

    def get_excel_data(self, fj_number, request):
        """获取创建EXCEL的数据"""
        today = datetime.date.today()
        year = today.year if today.month != 12 else today.year + 1
        month = today.month + 1 if today.month != 12 else 1
        _, num_days = calendar.monthrange(today.year, month)
        duty_arr = []
        if month < 10:
            currt_month = f"0{month}"
        else:
            currt_month = f"{month}"
        for i in range(1, num_days + 1):
            if i < 10:
                currt_day = f"0{i}"
            else:
                currt_day = f"{i}"

            one_line_sql = f"SELECT case when A.day_type = 'a' then '白班' else '夜班' END as day_type, B.real_name, B.mobile, B.job_number FROM (SELECT * FROM `personal_center_sortline` WHERE date='{year}-{currt_month}-{currt_day}' AND type='1') A LEFT JOIN tb_users_message B ON A.user_id=B.id"

            self.cur.execute(one_line_sql)
            one_line_data = self.cur.fetchall()
            one_line_list = []
            one_dict = {}
            one_dict['data'] = f'{month}月{i}日'
            for one in one_line_data:
                one_line_list.append(one[0])
                one_line_list.append(f'{one[1]}({one[2]})')
                one_line_list.append(one[3])
            one_dict['one_line'] = one_line_list
            two_line_sql = f"SELECT '夜班' as day_type, B.real_name, B.mobile, B.job_number FROM (SELECT * FROM `personal_center_sortline` WHERE date='{year}-{currt_month}-{currt_day}' AND type='2') A LEFT JOIN tb_users_message B ON A.user_id=B.id"

            self.cur.execute(two_line_sql)
            two_line_data = self.cur.fetchall()
            two_line_list = []
            for two in two_line_data:
                two_line_list.append('二线班')
                two_line_list.append(two[1])
                two_line_list.append(two[3])
            one_dict['two_line'] = two_line_list
            duty_arr.append(one_dict)
        days = f'0{today.day}' if today.day < 10 else today.day
        months = f'0{today.month}' if today.month < 10 else today.month
        file_path = f"/media/Topics_attachments/{year}/{months}/{days}/{fj_number}"
        file_name = f"{month}月总值班排班表（{year}年）.xlsx"
        if not os.path.exists(os.getcwd() + file_path):
            os.makedirs(os.getcwd() + file_path)
        topics_file_obj = Topicsattachments.objects.create(
            topics_number=fj_number, file_size='0kb', file_name=file_name,
            file_path=os.path.join(file_path.replace("/media/", ""), file_name), pdf_path=os.path.join(file_path, f"{month}月总值班排班表（{year}年）.pdf"),
            uploader=request.user.username, file_type='0', is_deleted=False, source='rspb',
            uploader_user=request.user
        )
        pdf_path = self.create_excel(duty_arr, os.path.join(os.getcwd() + file_path, file_name), month, file_name)
        topics_file_obj.pdf_path = pdf_path.replace(os.getcwd(), '')
        topics_file_obj.save()

    def create_excel(self, insert_data, excel_name, currt_month, file_name):
        """创建Excel"""
        wb = Workbook()
        ws = wb['Sheet']
        xw = wb.active
        ws.title = 'Sheet1'
        ws.merge_cells('A1:G1')
        ws.row_dimensions[1].height = 31
        top_left_cell = ws['A1']
        top_left_cell.value = f"京山市人民医院{currt_month}月值班表"
        top_left_cell.font = Font(b=True, color="000000", size=16)
        top_left_cell.alignment = Alignment(horizontal="center", vertical="center")
        thick_side = Side(border_style="thin", color="000000")
        border = Border(top=thick_side, left=thick_side, right=thick_side, bottom=thick_side)
        ws[f'A1'].alignment = Alignment(horizontal="center", vertical="center")
        xw[f'A1'].border = border
        row = 2
        for val in insert_data:
            if len(val["one_line"]) > 3:
                ws.merge_cells(f'A{row}:A{row+1}')
                ws.merge_cells(f'E{row}:E{row + 1}')
                ws.merge_cells(f'F{row}:F{row + 1}')
                ws.merge_cells(f'G{row}:G{row + 1}')
                ws[f'A{row}'].alignment = Alignment(horizontal="center", vertical="center")
                ws[f'B{row}'].alignment = Alignment(horizontal="center", vertical="center")
                ws[f'B{row + 1}'].alignment = Alignment(horizontal="center", vertical="center")
                ws[f'C{row}'].alignment = Alignment(horizontal="center", vertical="center")
                ws[f'C{row + 1}'].alignment = Alignment(horizontal="center", vertical="center")
                ws[f'D{row}'].alignment = Alignment(horizontal="center", vertical="center")
                ws[f'D{row + 1}'].alignment = Alignment(horizontal="center", vertical="center")
                ws[f'E{row}'].alignment = Alignment(horizontal="center", vertical="center")
                ws[f'F{row}'].alignment = Alignment(horizontal="center", vertical="center")
                ws[f'G{row}'].alignment = Alignment(horizontal="center", vertical="center")
                ws.cell(row, 1).value = val["data"]
                ws.cell(row, 2).value = val["one_line"][0]
                ws.cell(row + 1, 2).value = val["one_line"][3]
                ws.cell(row, 3).value = val["one_line"][1]
                ws.cell(row + 1, 3).value = val["one_line"][4]
                ws.cell(row, 4).value = val["one_line"][2]
                ws.cell(row + 1, 4).value = val["one_line"][5]
                ws.cell(row, 5).value = val["two_line"][0]
                ws.cell(row, 6).value = val["two_line"][1]
                ws.cell(row, 7).value = val["two_line"][2]
                ws.row_dimensions[row].height = 31
                ws.row_dimensions[row+1].height = 31
                ws[f'A{row}'].alignment = Alignment(horizontal="center", vertical="center")
                xw[f'A{row}'].border = border
                ws[f'B{row}'].alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
                xw[f'B{row}'].border = border
                ws[f'C{row}'].alignment = Alignment(horizontal="center", vertical="center")
                xw[f'C{row}'].border = border
                ws[f'D{row}'].alignment = Alignment(horizontal="center", vertical="center")
                xw[f'D{row}'].border = border
                ws[f'E{row}'].alignment = Alignment(horizontal="center", vertical="center")
                xw[f'E{row}'].border = border
                ws[f'F{row}'].alignment = Alignment(horizontal="center", vertical="center")
                xw[f'F{row}'].border = border
                ws[f'G{row}'].alignment = Alignment(horizontal="center", vertical="center")
                xw[f'G{row}'].border = border
                ws[f'A{row + 1}'].alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
                xw[f'A{row + 1}'].border = border
                ws[f'B{row + 1}'].alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
                xw[f'B{row + 1}'].border = border
                ws[f'C{row + 1}'].alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
                xw[f'C{row + 1}'].border = border
                ws[f'D{row + 1}'].alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
                xw[f'D{row + 1}'].border = border
                ws[f'E{row + 1}'].alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
                xw[f'E{row + 1}'].border = border
                ws[f'F{row + 1}'].alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
                xw[f'F{row + 1}'].border = border
                ws[f'G{row + 1}'].alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
                xw[f'G{row + 1}'].border = border
                row += 2
            else:
                ws[f'A{row}'].alignment = Alignment(horizontal="center", vertical="center")
                ws[f'B{row}'].alignment = Alignment(horizontal="center", vertical="center")
                ws[f'C{row}'].alignment = Alignment(horizontal="center", vertical="center")
                ws[f'D{row}'].alignment = Alignment(horizontal="center", vertical="center")
                ws[f'E{row}'].alignment = Alignment(horizontal="center", vertical="center")
                ws[f'F{row}'].alignment = Alignment(horizontal="center", vertical="center")
                ws[f'G{row}'].alignment = Alignment(horizontal="center", vertical="center")
                ws.cell(row, 1).value = val["data"]
                ws.cell(row, 2).value = val["one_line"][0]
                ws.cell(row, 3).value = val["one_line"][1]
                ws.cell(row, 4).value = val["one_line"][2]
                ws.cell(row, 5).value = val["two_line"][0]
                ws.cell(row, 6).value = val["two_line"][1]
                ws.cell(row, 7).value = val["two_line"][2]
                ws.row_dimensions[row].height = 31
                ws[f'A{row}'].alignment = Alignment(horizontal="center", vertical="center")
                xw[f'A{row}'].border = border
                ws[f'B{row}'].alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
                xw[f'B{row}'].border = border
                ws[f'C{row}'].alignment = Alignment(horizontal="center", vertical="center")
                xw[f'C{row}'].border = border
                ws[f'D{row}'].alignment = Alignment(horizontal="center", vertical="center")
                xw[f'D{row}'].border = border
                ws[f'E{row}'].alignment = Alignment(horizontal="center", vertical="center")
                xw[f'E{row}'].border = border
                ws[f'F{row}'].alignment = Alignment(horizontal="center", vertical="center")
                xw[f'F{row}'].border = border
                ws[f'G{row}'].alignment = Alignment(horizontal="center", vertical="center")
                xw[f'G{row}'].border = border
                row += 1
        ws.column_dimensions['A'].width = 11
        ws.column_dimensions['B'].width = 10
        ws.column_dimensions['c'].width = 22
        ws.column_dimensions['D'].width = 11
        ws.column_dimensions['E'].width = 10
        ws.column_dimensions['F'].width = 12
        ws.column_dimensions['G'].width = 12
        wb.save(excel_name)
        b = xlrd.open_workbook(excel_name)
        sheetnum = len(b.sheets())
        pdfConverter = PDFConverter(excel_name, sheetnum, os.path.splitext(file_name)[0])
        pdf_path = pdfConverter.run_conver()
        return pdf_path[0]


    def send_meail(self, fj_number, send_user):
        """值班邮件发送"""
        now = datetime.datetime.now()
        Y = now.year
        M = now.month
        D = now.day
        next_month = now.month + 1
        if next_month == 13:  # 如果下个月是 13，即为明年 1 月
            next_month = 1
        serial_content = f"总值班：{next_month}月份总值班排班已发至您OA邮箱，请查收。"

        res = send_mssage(list(set(self.meseage_tel_li)), serial_content)  # 发送短信

        file_name = f"{next_month}月份总值班排班"

        time_str = f"{Y} 年 {M} 月 {D} 日"
        message_content = f'<p></br></p><p><br/></p><p>总值班：{file_name}</p><p><br/></p><p><br/></p><p><br/></p><p>&nbsp; &nbsp; &nbsp; &nbsp;' \
                          f'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;' \
                          f'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;' \
                          f'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ' \
                          f'{time_str}</p><p><br style="white-space: normal;"/></p><p><br/></p>'

        InboxInfo_obj = InboxInfo.objects.create(
            content=message_content,
            plain_text=f'总值班：{next_month}月份总值班排班。  {time_str}',
            title=file_name,
            accessory_uuid=fj_number,
            is_draft=False,
            proposer=send_user
        )
        select_user_sql = "SELECT user_id FROM `administration`.`personal_center_scheduling`"
        self.cur.execute(select_user_sql)
        job_num_list = self.cur.fetchall()
        for i in job_num_list:
            user_obj = User.objects.get(id=i[0])
            InboxInfoPeople.objects.create(
                inbox_id=InboxInfo_obj,
                recipient=user_obj,
                recipient_name=f"{user_obj.real_name}<{user_obj.job_number}>"
            )

    def ClearAndCopyData(self):
        """清空临时表数据，并将正式表中的数据复制到临时表中去"""
        clear_sql = "TRUNCATE TABLE `personal_center_schedulingcopy`"
        self.cur.execute(clear_sql)

        select_sql = "SELECT * FROM personal_center_scheduling"
        self.cur.execute(select_sql)
        select_data = self.cur.fetchall()
        for sel_da in select_data:
            insert_data = f"INSERT INTO personal_center_schedulingcopy (create_time, update_time, type, user_id, day_type, is_work, date, last_date) VALUES(" \
                          f"NOW(), NOW(), '{sel_da[3]}', '{sel_da[4]}', '{sel_da[5]}', '{sel_da[6]}', '{sel_da[7]}', '{sel_da[8]}')"
            self.cur.execute(insert_data)
            self.conn.commit()

    def FirstLineWork(self):
        """一线班排班"""
        today = datetime.date.today()
        year = today.year if today.month != 12 else today.year + 1
        month = today.month + 1 if today.month != 12 else 1

        search_data = f"{year}-0{month}-01" if month < 10 else f"{year}-{month}-01"
        print("search_data: ", search_data)
        data_sql = f"SELECT * FROM `personal_center_sortline` where date='{search_data}'"
        self.cur.execute(data_sql)
        datas = self.cur.fetchall()
        if datas:
            return []

        select_sql = f"SELECT id FROM `administration`.`{self.OperationTable}` WHERE `is_work` = '1' AND `type` = '1'"
        self.cur.execute(select_sql)
        id_number = self.cur.fetchall()[0][0]  # 当前月一线班最后一位值班人员

        _, num_days = calendar.monthrange(today.year, month)

        for i in range(1, num_days+1):
            # 更新排班表二线班值班状态
            updata_sql = f"UPDATE `administration`.`{self.OperationTable}` SET is_work='0' WHERE id='{id_number}'"
            self.cur.execute(updata_sql)
            self.conn.commit()
            id_number += 1
            try:
                select_duty_leader = f"SELECT user_id FROM `administration`.`{self.OperationTable}` WHERE id='{id_number}' AND `type` = '1'"
                self.cur.execute(select_duty_leader)
                duty_leader1 = self.cur.fetchall()[0][0]  # 值班人员


                updata_duty_leader_sql = f"UPDATE `administration`.`{self.OperationTable}` SET is_work='1' WHERE id='{id_number}'"
                self.cur.execute(updata_duty_leader_sql)
                self.conn.commit()
            except Exception as EF:
                # 查询二线班的第一位领导
                select_first_leader_sql = f"SELECT id FROM `administration`.`{self.OperationTable}` WHERE `type` = '1'"
                self.cur.execute(select_first_leader_sql)
                id_number = self.cur.fetchall()[0][0]

                select_duty_leader = f"SELECT user_id FROM `administration`.`{self.OperationTable}` WHERE id='{id_number}'"
                self.cur.execute(select_duty_leader)
                duty_leader1 = self.cur.fetchall()[0][0]  # 值班领导

                updata_duty_leader_sql = f"UPDATE `administration`.`{self.OperationTable}` SET is_work='1' WHERE id='{id_number}'"
                self.cur.execute(updata_duty_leader_sql)
                self.conn.commit()

            first_day_of_next_month = datetime.date(year, month, i)  # 例如：2024-06-01
            JudgmentFlag = self.DateJudgment(first_day_of_next_month)  # 是否是工作日
            user_sql = f"SELECT real_name, job_number, mobile FROM `tb_users_message` WHERE id={duty_leader1}"
            self.cur.execute(user_sql)
            user_obj = self.cur.fetchall()
            weekday_str = self.get_weekday(f"{year}-{month}-{i}")
            one_dict = {"data": f"{year}{month}{i}", "time": f"{month}月{i}日", "weekday": weekday_str, "Judgment": JudgmentFlag, "one_line_work": [{"name": user_obj[0][0], "job_number": user_obj[0][1], "mobile": user_obj[0][2], "day_type": "白班" if JudgmentFlag == 2 else "夜班"}]}

            if self.OperationTable == "personal_center_scheduling":
                sql_day_type = "a" if JudgmentFlag == 2 else "b"
                insert_sql = f"INSERT INTO `personal_center_sortline` (type, date, user_id, day_type, is_deleted) VALUES('1', '{first_day_of_next_month}', {duty_leader1}, '{sql_day_type}', '0')"
                self.cur.execute(insert_sql)
                self.conn.commit()
                self.meseage_tel_li.append(User.objects.get(id=duty_leader1).mobile)

            if JudgmentFlag == 2:
                updata_sql = f"UPDATE `administration`.`{self.OperationTable}` SET is_work='0' WHERE id='{id_number}'"
                self.cur.execute(updata_sql)
                self.conn.commit()
                id_number += 1
                try:
                    select_duty_leader = f"SELECT user_id FROM `administration`.`{self.OperationTable}` WHERE id='{id_number}' AND `type` = '1'"
                    self.cur.execute(select_duty_leader)
                    duty_leader2 = self.cur.fetchall()[0][0]  # 值班人员

                    updata_duty_leader_sql = f"UPDATE `administration`.`{self.OperationTable}` SET is_work='1' WHERE id='{id_number}'"
                    self.cur.execute(updata_duty_leader_sql)
                    self.conn.commit()
                except Exception as EF:
                    print("错误提示：", EF)
                    # 查询二线班的第一位领导
                    select_first_leader_sql = f"SELECT id FROM `administration`.`{self.OperationTable}` WHERE `type` = '1'"
                    self.cur.execute(select_first_leader_sql)
                    id_number = self.cur.fetchall()[0][0]

                    select_duty_leader = f"SELECT user_id FROM `administration`.`{self.OperationTable}` WHERE id='{id_number}'"
                    self.cur.execute(select_duty_leader)
                    duty_leader2 = self.cur.fetchall()[0][0]  # 值班领导

                    updata_duty_leader_sql = f"UPDATE `administration`.`{self.OperationTable}` SET is_work='1' WHERE id='{id_number}'"
                    self.cur.execute(updata_duty_leader_sql)
                    self.conn.commit()

                user_sql = f"SELECT real_name, job_number, mobile FROM `tb_users_message` WHERE id={duty_leader2}"
                self.cur.execute(user_sql)
                user_obj = self.cur.fetchall()
                one_dict["one_line_work"].append({"name": user_obj[0][0], "job_number": user_obj[0][1], "mobile": user_obj[0][2], "day_type": "夜班"})

                if self.OperationTable == "personal_center_scheduling":
                    insert_sql1 = f"INSERT INTO `personal_center_sortline` (type, date, user_id, day_type, is_deleted) VALUES('1', '{first_day_of_next_month}', {duty_leader2}, 'b', '0')"
                    self.cur.execute(insert_sql1)
                    self.conn.commit()
                    self.meseage_tel_li.append(User.objects.get(id=duty_leader2).mobile)

            self.SchedulingList.append(one_dict)

    def SecondLineWork(self):
        """二线班排班"""
        select_sql = f"SELECT id FROM `administration`.`{self.OperationTable}` WHERE `is_work` = '1' AND `type` = '2'"
        self.cur.execute(select_sql)
        id_number = self.cur.fetchall()[0][0]  # 当前月二线班最后一位值班领导

        today = datetime.date.today()
        year = today.year if today.month != 12 else today.year + 1
        month = today.month + 1 if today.month != 12 else 1

        _, num_days = calendar.monthrange(today.year, month)

        for i in range(1, num_days+1):
            first_day_of_next_month = datetime.date(year, month, i)
            try:
                # 更新排班表二线班值班状态
                updata_sql = f"UPDATE `administration`.`{self.OperationTable}` SET is_work='0' WHERE id='{id_number}'"
                self.cur.execute(updata_sql)
                self.conn.commit()

                id_number += 1
                try:
                    select_duty_leader = f"SELECT user_id FROM `administration`.`{self.OperationTable}` WHERE id='{id_number}'"
                    self.cur.execute(select_duty_leader)
                    duty_leader3 = self.cur.fetchall()[0][0]                  # 值班领导
                    self.duty_leader_list.append(duty_leader3)

                    updata_duty_leader_sql = f"UPDATE `{self.OperationTable}` SET is_work='1' WHERE id='{id_number}'"
                    self.cur.execute(updata_duty_leader_sql)
                    self.conn.commit()
                except Exception as EF:
                    # 查询二线班的第一位领导
                    select_first_leader_sql = f"SELECT id FROM `administration`.`{self.OperationTable}` WHERE `type` = '2'"
                    self.cur.execute(select_first_leader_sql)
                    id_number = self.cur.fetchall()[0][0]  # 当前月二线班最后一位值班领导

                    select_duty_leader = f"SELECT user_id FROM `administration`.`{self.OperationTable}` WHERE id='{id_number}'"
                    self.cur.execute(select_duty_leader)
                    duty_leader3 = self.cur.fetchall()[0][0]  # 值班领导
                    self.duty_leader_list.append(duty_leader3)

                    updata_duty_leader_sql = f"UPDATE `{self.OperationTable}` SET is_work='1' WHERE id='{id_number}'"
                    self.cur.execute(updata_duty_leader_sql)
                    self.conn.commit()

                user_sql = f"SELECT real_name, job_number, mobile FROM `tb_users_message` WHERE id={duty_leader3}"
                self.cur.execute(user_sql)
                user_obj = self.cur.fetchall()

                for ii in self.SchedulingList:
                    if ii["data"] == f"{year}{month}{i}":
                        ii["second_line_work"] = {"name": user_obj[0][0], "job_number": user_obj[0][1], "mobile": user_obj[0][2], "day_type": "白班"}

                if self.OperationTable == "personal_center_scheduling":
                    insert_sql = f"INSERT INTO `personal_center_sortline` (type, date, user_id, day_type, is_deleted) VALUES('2', '{first_day_of_next_month}', {duty_leader3}, 'a', '0')"
                    self.cur.execute(insert_sql)
                    self.conn.commit()
            except Exception as ER:
                print(ER)

    def main_fun(self, request):
        # 每年12月更新 chinesecalendar 库
        # if datetime.datetime.now().month == 12:
        #     self.UpgradeInstallationPackage()

        # 删除临时表中的数据，并将正式表中的数据复制到临时表中去
        self.ClearAndCopyData()

        self.FirstLineWork()
        self.SecondLineWork()

        if self.OperationTable == "personal_center_scheduling":
            fj_number = uuid.uuid4()
            self.send_meail(fj_number, request.user)
            self.get_excel_data(fj_number, request)

        self.cur.close()
        self.conn.close()

        return self.SchedulingList



# 定义函数来创建一个月份的日历
class create_calendar():
    def get_calendar(self, year, month, current_day, currt_user):
        # 获取月份的第一天是周几
        first_day_of_month = datetime.datetime(year, month, 1)
        weekday = first_day_of_month.weekday()
        # 初始化一个空的日历列表
        calendar_lines = []
        one_list = []
        flag = True
        TraveCount = ''
        # 迭代一个月的所有天数
        current_date = datetime.datetime(year, month, 1)
        current_flag = 'true'
        while current_date.month == month:
            day = current_date.day
            # 在日历的相应位置填充天数
            if weekday != 1 and flag:
                flag = False
                for i in range(1, weekday + 1):
                    if current_flag == 'true':
                        trave_time = f'{(first_day_of_month - timedelta(days=i)).year}-{(first_day_of_month - timedelta(days=i)).month}-{(first_day_of_month - timedelta(days=i)).day}'
                        TraveCount = TravelApply.objects.filter(start_time__lte=trave_time, end_time__gte=trave_time, state="five", apply_user=currt_user).count()
                    one_list.insert(0, {"year": (first_day_of_month - timedelta(days=i)).year, "status": 0,
                                        "month": (first_day_of_month - timedelta(days=i)).month,
                                        "day": (first_day_of_month - timedelta(days=i)).day, "current_before": current_flag, "trave_flag": 'true' if TraveCount else "false"})
            if day < 10:
                currt_day = f"0{day}"
            else:
                currt_day = day
            if current_flag == 'true':
                trave_time = f'{current_date.year}-{current_date.month}-{currt_day} 00:00:00'
                TraveCount = TravelApply.objects.filter(start_time__lte=trave_time, end_time__gte=trave_time, state="five", apply_user=currt_user).count()
                print(trave_time, TraveCount)
            one_list.append({"year": current_date.year, "status": 1, "month": current_date.month, "day": day, "current_before": current_flag, "trave_flag": 'true' if TraveCount else "false"})
            if year == current_date.year and month == current_date.month and current_day == day:
                current_flag = 'false'
            weekday = current_date.weekday()
            # 如果到了新的周，添加一个新的行
            if len(one_list) == 7:
                calendar_lines.append(one_list)
                one_list = []

            current_date += timedelta(days=1)
            if current_date.month != month and len(one_list) <= 7:
                for j in range(0, 7 - len(one_list)):
                    if current_date.day + j < 10:
                        currt_day = f"0{current_date.day + j}"
                    else:
                        currt_day = current_date.day + j
                    if current_flag == 'true':
                        trave_time = f'{current_date.year}-{current_date.month}-{currt_day}'
                        TraveCount = TravelApply.objects.filter(start_time__lte=trave_time, end_time__gte=trave_time, state="five", apply_user=currt_user).count()
                    one_list.append({"year": current_date.year, "status": 0, "month": current_date.month,
                                     "day": current_date.day + j, "current_before": current_flag, "trave_flag": 'true' if TraveCount else "false"})
                calendar_lines.append(one_list)

            if len(calendar_lines) != 6 and current_date.month != month:
                one_list = []
                for k in range(calendar_lines[4][6]['day'] + 1, calendar_lines[4][6]['day'] + 8):
                    if k < 10:
                        currt_day = f"0{k}"
                    else:
                        currt_day = k
                    if current_flag == 'true':
                        trave_time = f'{current_date.year}-{current_date.month}-{currt_day}'
                        TraveCount = TravelApply.objects.filter(start_time__lte=trave_time, end_time__gte=trave_time, state="five", apply_user=currt_user).count()
                    one_list.append({"year": current_date.year, "status": 0, "month": current_date.month, "day": k, "current_before": current_flag, "trave_flag": 'true' if TraveCount else "false"})
                calendar_lines.append(one_list)
        return calendar_lines


if __name__ == '__main__':
    development = 'test'
    types = 'scheduling'            # 排班
    # types = 'pre_scheduling'  # 预排班
    # AutomaticScheduling(development, types).main_fun()